﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using Newtonsoft.Json;
using SilverlightRest.Web.Compression;
using SilverlightRest.Web.Filters;

namespace SilverlightRest.Web
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // Serialization settings
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Binder = new TypeNameSerializationBinder();
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;

            GlobalConfiguration.Configuration.Filters.Add(new HeaderFilter());

            GlobalConfiguration.Configuration.MessageHandlers.Add(new CompressionHandler());

            GlobalConfiguration.Configure(WebApiConfig.Register);

            Bootstrapper.Initialise();
        }
    }

    public class TypeNameSerializationBinder : SerializationBinder
    {
        public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
        {
            assemblyName = serializedType.Assembly.FullName;
            typeName = serializedType.FullName;

            
        }

        public override Type BindToType(string assemblyName, string typeName)
        {
            string resolvedTypeName;
            if (assemblyName == "mscorlib")
            {
                resolvedTypeName = string.Format("{0},{1}", typeName, assemblyName);
                resolvedTypeName = resolvedTypeName.Replace("MyDomainSilverlight]", "MyDomain, Version=1.0.0.0]");
            }
            else
                resolvedTypeName = string.Format("{0}, MyDomain, Version=1.0.0.0, Culture=neutral", typeName);

            return Type.GetType(resolvedTypeName, true);
        }
    }
}